'''
This file is a part of nets7r project
Licensed under New BSD license
H3n0xek (C) 2011 
'''
from services.identifier.api import register, unregister
from excepts import IdentRegistrationFail, IdentUnregistrationFail

class StateObject(object):
    """Defines object which has a state between on/off"""
    def __init__(self):
        """Default constructor creates object
            with state = False (turned off)"""
        super(StateObject, self).__init__()
        self._state = False
        
    def _get_state(self):
        """State property getter"""
        return self._state
    
    def _set_state(self, new_state):
        """State property setter"""
        self._state = (new_state == True)

    state = property(_get_state, _set_state)
    


class IdentifiedObject(object):
    """Defines object which has an autoincrement ID field
    defined in this object type
     
    Use it in derived class constructor as this:
        super(ChildClass, self).__init__()
    or
        super(ChildClass, self).__init__(ClassType)
         
    All objects of this type have ID property"""
    def __init__(self, cls=None):
        """Assign new ID when creating"""
        super(IdentifiedObject, self).__init__()
        if not cls:
            cls = self.__class__
        self._cls = cls
        self._id = register(cls, self)
        if not self._id:
            raise IdentRegistrationFail(self, cls)
                
    def _get_id(self):
        return self._id    
    
    ID = property(_get_id)
    
    def __del__(self):
        """Releases ID of current object"""
        if not unregister(self._id):
            raise IdentUnregistrationFail(self._id, self._cls)

